package com.gljx.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.Oilspec;
import com.gljx.web.Entity.OtherCarAddOil;
import com.gljx.web.Entity.OtherCarAddOilEntry;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.Person;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.OilspecService;
import com.gljx.web.service.OtherCarAddOilService;
import com.gljx.web.service.PersonService;

@Controller
@RequestMapping("/")
public class OtherCarAddOilController {

	
	//自动注入
	@Autowired
	private OtherCarAddOilService otherCarAddOilService;
	
	//自动注入
	@Autowired
	private OilspecService oilspecService;
	
	//自动注入
	@Autowired
	private DepartmentService departmentService;
	
	//自动注入
	@Autowired
	private CustomLogService customLogService;
	
	//自动注入
	@Autowired
	private PersonService personService;
	
	/**
	 * 查询其他车辆加油登记
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryOtherCarAddOil/look.action")
	public String queryOtherCarAddOil(HttpServletRequest request, String flag) {
		PageBean<OtherCarAddOil> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<OtherCarAddOil> otherCarAddOils = pb.getBeanList();
			for (OtherCarAddOil otherCarAddOil : otherCarAddOils) {
				//查询子类信息
				List<OtherCarAddOilEntry> otherCarAddOilEntrys = otherCarAddOilService.queryOtherCarAddOilEntryMapper(otherCarAddOil.getFid(), "", "");
				//放入集合
				otherCarAddOil.setOtherCarAddOilEntrys(otherCarAddOilEntrys);
			}

			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("otherCarAddOils", otherCarAddOils);
			request.setAttribute("pb", pb);
			request.setAttribute("flag", flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/otherCarAddOil/otherCarAddOilList";
	}


	/**
	 * 根据车辆名称查询车辆历史信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping (value = "/selCarAddOilByName")
	public OtherCarAddOilEntry selCarAddOilByName(String carName, HttpServletRequest request) {
		List<OtherCarAddOilEntry> list = otherCarAddOilService.selectOtherCarAddOilByInfo(GetUserSession.getUserSession(request),"","",carName,"","");
		OtherCarAddOilEntry otherCarAddOilEntry = new OtherCarAddOilEntry();
		if(!list.isEmpty()) {
			otherCarAddOilEntry = list.get(0);
		}
		return otherCarAddOilEntry;
	}

	/**
	 * 很据条件查询其他车辆加油登记
	 * @param request
	 * @param addoilName 加油人
	 * @param cfdept 部门
	 * @param cfcar 车辆
	 * @param beginTime 业务开始时间
	 * @param endTime 业务结束时间
	 * @return
	 */
	@RequestMapping("/queryOtherCarAddOilByInfo")
	public String queryOtherCarAddOilByInfo(HttpServletRequest request,String addoilName,String cfdept,String cfcar,String beginTime,String endTime){
		PageBean<OtherCarAddOil> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
			addoilName = addoilName.trim();
			cfdept = cfdept.trim();
			cfcar = cfcar.trim();
			//获取分页
			pb = getPageBean2(request,user.getFcompanyid(),addoilName,cfdept,cfcar,beginTime,endTime);
			//获取分页数据
			List<OtherCarAddOil> otherCarAddOils = pb.getBeanList();
			for (OtherCarAddOil otherCarAddOil : otherCarAddOils) {
				//查询子类信息
				List<OtherCarAddOilEntry> otherCarAddOilEntrys = otherCarAddOilService.queryOtherCarAddOilEntryMapper(otherCarAddOil.getFid(), cfdept, cfcar);
				//放入集合
				otherCarAddOil.setOtherCarAddOilEntrys(otherCarAddOilEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("otherCarAddOils", otherCarAddOils);
			request.setAttribute("pb", pb);
			request.setAttribute("addoilName", addoilName);
			request.setAttribute("cfdept", cfdept);
			request.setAttribute("cfcar", cfcar);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/otherCarAddOil/otherCarAddOilList";
	}
	
	/**
	 * 跳转到添加二面
	 * @param request
	 * @param type
	 * @return
	 */
	@RequestMapping("/insertOtherCarAddOil")
	public String insertOtherCarAddOil(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("CT_DS_OTHERCARADDOIL",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("QTJY");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//时间
		String time = sdf.format(new Date());
		//查询汽油规格
		List<Oilspec> oilspecs = oilspecService.queryOilsperAll();
		//查询职员
		//拼接SQL语句
    	StringBuffer psql = new StringBuffer();
    	psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		//查询职员
		List<Person> persons = personService.selectPerson(psql.toString());
		//把数据传到页面
		request.setAttribute("persons", persons);
		request.setAttribute("oilspecs", oilspecs);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		request.setAttribute("time", time);
		return "/backHome/carManagement/otherCarAddOil/editOtherCarAddOil";
	}
	
	/**
	 * 根据名称查询汽油规格
	 * @param name
	 * @return
	 */
	@RequestMapping("/queOilspecByName")
	@ResponseBody
	public List<Oilspec> queOilspecByName(String name){
		List<Oilspec> oilspecs = new ArrayList<>();
		if(name == null || "".equals(name)){
			oilspecs = oilspecService.queryOilsperAll();
		}else{
			oilspecs = oilspecService.queryOilsperByName(name);
		}
		return oilspecs;
	}
	
	/**
	 * 添加，或修改
	 * @param request
	 * @param fid
	 * @param otherCarAddOil
	 * @return
	 */
	@RequestMapping("/editOtherCarAddOil")
	public String editOtherCarAddOil(HttpServletRequest request,String fid,OtherCarAddOil otherCarAddOil){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		otherCarAddOil.setFcontrolunitid(user.getFcompanyid());
		//公司id
		otherCarAddOil.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		otherCarAddOil.setFhandlerid(user.getFid());
		/**获取子类信息集合**/
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//车辆
		String[] cfcar = request.getParameterValues("cfcar");
		//部门
		String[] cfdept = request.getParameterValues("cfdept");
		//汽油规格id
		String[] cfoilspecification = request.getParameterValues("cfoilspecification");
		//数量
		String[] cfqty = request.getParameterValues("cfqty");
		//备注
		String[] cfremarks = request.getParameterValues("cfremarks");
		//添加或修改
		otherCarAddOilService.editOtherCarAddOil(otherCarAddOil,fseq,cfcar,cfdept,cfoilspecification,cfqty,cfremarks,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
			customLogService.addLog("车辆管理", time+"对其他车辆加油登记进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertOtherCarAddOil?type=3";
		}else{
			//添加日志
			customLogService.addLog("车辆管理", time+"对其他车辆加油登记进行修改操作", null, user.getFid());
			//重定向到查询页面
			return "redirect:/DrivingSys/queryOtherCarAddOil/look.action?flag=1";
		}
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryOtherCarAddOilByFid")
	public String queryOtherCarAddOilByFid(HttpServletRequest request,String fid){
		//查询父类信息
		OtherCarAddOil otherCarAddOil = otherCarAddOilService.queryOtherCarAddOilByFid(fid);
		//查询子类信息
		List<OtherCarAddOilEntry> otherCarAddOilEntrys = otherCarAddOilService.queryOtherCarAddOilEntryMapper(fid, "", "");
		//查询汽油规格
		List<Oilspec> oilspecs = oilspecService.queryOilsperAll();
		//查询职员
		//拼接SQL语句
    	StringBuffer psql = new StringBuffer();
    	psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		//查询职员
		List<Person> persons = personService.selectPerson(psql.toString());
        //查询是否是经办人
        Axamine axamine = new Axamine();
        boolean state = axamine.selectAuditPersonByAdd(otherCarAddOil.getFnumber(), ActivitiKey.PUBLIC_KEY);
        //把数据传到页面
        request.setAttribute("AuditState", state);
        request.setAttribute("otherCarAddOil", otherCarAddOil);
		request.setAttribute("otherCarAddOilEntrys", otherCarAddOilEntrys);
		request.setAttribute("persons", persons);
		request.setAttribute("oilspecs", oilspecs);
        request.setAttribute("key", ActivitiKey.PUBLIC_KEY);
        return "/backHome/carManagement/otherCarAddOil/editOtherCarAddOil";
	}
	
	/**
	 * 审核，反审核
	 * @param request
	 * @param type 1：审核，2：反审核
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditOtherCarAddOil")
	@ResponseBody
	public int auditOtherCarAddOil(HttpServletRequest request, String type, String fid, String message, String state, String fnumber) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//审核，反审核
		int i = otherCarAddOilService.auditOtherCarAddOil(fid, type, user.getFid(), message, state, fnumber);
		//添加日志
		customLogService.addLog("车辆管理", "对其他车辆加油登记进行审核操作单据编号 " + fnumber, null, user.getFid());
		return i;
	}

	/**
	 * 提交
	 *
	 * @param fid
	 * @return
	 */
	@RequestMapping("/submitOtherCarAddOil")
	@ResponseBody
    public int submitOtherCarAddOil(String fid, HttpServletRequest request, String fnumber, String auditState) {
        OtherCarAddOil otherCarAddOil = new OtherCarAddOil();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		otherCarAddOil.setFid(fid);
		otherCarAddOil.setFlastupdateuserid(user.getFid());
		otherCarAddOil.setCfbillstate(4L);
		//创建流程
		Axamine axamine = new Axamine();
        axamine.submissionProcess(fnumber);
        int i = otherCarAddOilService.submitOtherCarAddOil(otherCarAddOil);
		//添加日志
		customLogService.addLog("车辆管理", "对其他车辆加油登记进行提交操作单据编号 " + fnumber, null, user.getFid());
		return i;
	}

	/**
	 * 根据fid删除
	 * @param request
	 * @param fid 单个
	 * @param deleteId 多个
	 * @return
	 */
	@RequestMapping("/deleteOtherCarAddOilByFid")
    public String deleteOtherCarAddOilByFid(HttpServletRequest request, String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
        otherCarAddOilService.deleteOtherCarAddOilByFid(fid, deleteId, fnumber, fnumber2);
        //添加日志
		customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date())+"对其他车辆加油登记进行修改操作", null, user.getFid());
		//重定向到查询页面
		return "redirect:/DrivingSys/queryOtherCarAddOil/look.action";
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<OtherCarAddOil> getPageBean2(HttpServletRequest request,String companyId,String addoilName,String cfdept,String cfcar,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate,p.fname_l2 addoilName ");
		psql.append("from CT_DS_OTHERCARADDOIL t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid left join ct_ds_person p ");
		psql.append("on t.cfaddoilpersonid = p.fid left join ct_ds_othercaraddoilentry o on t.fid = o.fparentid where t.fcontrolunitid = '"+companyId+"'");
		if("".equals(addoilName)){
			
		}else{
			psql.append(" and p.fname_l2 like '%"+addoilName+"%'");
		}
		if("".equals(cfdept)){
			
		}else{
			psql.append(" and o.cfdept like '%"+cfdept+"%'");
		}
		if("".equals(cfcar)){
			
		}else{
			psql.append(" and o.cfcar like  '%"+cfcar+"%'");
		}
		if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= otherCarAddOilService.selectPage(pindex, psql.toString(), psize);
		PageBean<OtherCarAddOil> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<OtherCarAddOil>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<OtherCarAddOil> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate,p.fname_l2 addoilName from ");
		psql.append(" CT_DS_OTHERCARADDOIL t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid left join ct_ds_person p ");
		psql.append(" on t.cfaddoilpersonid = p.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= otherCarAddOilService.selectPage(pindex, psql.toString(), psize);
		PageBean<OtherCarAddOil> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<OtherCarAddOil>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=otherCarAddOilService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param addoilName
     * @param cfdept
     * @param cfcar
     * @param beginTime
     * @param endTime
     */
    @RequestMapping("/importOtherCarAddOil")
    public void importOtherCarAddOil(HttpServletRequest request, HttpServletResponse response, String addoilName,
                                     String cfdept, String cfcar, String beginTime, String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<OtherCarAddOilEntry> otherCarAddOilEntrys = otherCarAddOilService.selectOtherCarAddOilByInfo(user.getFcompanyid(), addoilName.trim(), cfdept.trim(), cfcar.trim(), beginTime, endTime);
        for (OtherCarAddOilEntry otherCarAddOilEntry : otherCarAddOilEntrys) {
            data.add(otherCarAddOilEntry.getFnumber());
            data.add(otherCarAddOilEntry.getFbizdate());
            data.add(otherCarAddOilEntry.getFdescription());
            data.add(otherCarAddOilEntry.getShName());
            data.add(otherCarAddOilEntry.getZdrName());
            data.add(otherCarAddOilEntry.getPersonName());
            data.add(stateToString.billsState(otherCarAddOilEntry.getCfbillstate()));
            data.add(otherCarAddOilEntry.getOilName());
            data.add(otherCarAddOilEntry.getCfqty());
            data.add(otherCarAddOilEntry.getCfremarks());
            data.add(otherCarAddOilEntry.getCfcar());
            data.add(otherCarAddOilEntry.getCfdept());
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "备注", "审核人名称", "制单人名称", "加油人", "单据状态", "汽油规格", "加油量(公升)", "备注", "车辆", "部门"};
        //长度
        Integer length[] = {8000, 4000, 5000, 3000, 3000, 3000, 2600, 3000, 4000, 4000, 4000, 3000};
        try {
            //导出Excel
            CommonExport.importExcel(response, "其他车辆加油" + TimeFormat.getNowTime2() + ".xls", "其他车辆加油", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
